//页面加载  
$(document).ready(function(){
	$('#dataGridTable').treegrid({
		fit:true,
		url:'sys/queryDepartment.action',
		toolbar:'#toolbar',
		idField:'departmentCode',
	    treeField:'departmentName',
	    singleSelect:true,
	    striped:true,
		fitColumns:false,
		rownumbers:true,
		pagination:false,
		checkOnSelect:true,
		columns:[[
		          {field:'departmentId',title:'组织架构ID',width:80,hidden:true,align:'center'},
		          {field:'departmentName',title:'组织名称',width:300},
                  {field:'departmentCode',title:'组织编码',width:100,align:'center'},
                  {field:'departmentState',title:'组织状态',width:100,align:'center',formatter:areaSatuts},
                  {field:'createUser',title:'记录建立者',width:createUserWidth,align:'center'},
                  {field:'createTime',title:'记录建立时间',width:createTimeWidth,align:'center'},
                  {field:'lastModifiedUser',title:'记录最后修改者',width:lastModifiedWidth,align:'center'},
                  {field:'lastModifiedTime',title:'记录最后修改时间',width:createTimeWidth,align:'center'}
              ]],
        onClickRow:function(row){
        	var disableBtnFlag = false;
        	var enableBtnFlag = false;
        	//获得name值
    		for(var i=0;i<resource.length;i++){
    			var disableBtnName = $('#disableBtn').attr("name");
    			if(resource[i].trim()==disableBtnName.trim())
    			{
    				disableBtnFlag = true;
    			}
    			if(resource[i].trim()==$('#enableBtn').attr("name"))
    			{
    				enableBtnFlag = true;
    			}
    		}
			if(1==row.departmentState && !disableBtnFlag){
				$('#disableBtn').linkbutton("enable");
				$('#enableBtn').linkbutton("disable");
			}else{
				$('#disableBtn').linkbutton("disable");
			}
			if(0==row.departmentState && !enableBtnFlag){
				$('#enableBtn').linkbutton("enable");
				$('#disableBtn').linkbutton("disable");
			}else{
				$('#enableBtn').linkbutton("disable");
			}
		}
	});
	 $('#enableBtn').linkbutton({
		 onClick:function(){
			 enableDepartment('1');
		 }
	 });
	 $('#disableBtn').linkbutton({
		 onClick:function(){
			 enableDepartment('0')
		 }
	 });
	 //添加回车事件
	 $('#searchDeptCode').textbox('textbox').keydown(function (e) {
		   if (e.keyCode == 13) {
			   $('#searchDeptCode').textbox('setValue', $(this).val());
			   query();
		    }
		});
	 $('#searchDeptName').textbox('textbox').keydown(function (e) {
		   if (e.keyCode == 13) {
			   $('#searchDeptName').textbox('setValue', $(this).val());
			   query();
		    }
		});
	//最后初始化表单dialog
	openDepartmentDialog();
	closeDepartmentDialog();
});

//改变组织状态
function enableDepartment(value){
	//获取grid选中的数据
	var selectedData = $('#dataGridTable').datagrid('getSelections');
	if(selectedData.length > 0){
		var data = selectedData[0];
		var departmentId = data.departmentId;
		var operator = value == 0 ? "禁用":"启用";
		var deptName = data.departmentName;
		$.messager.confirm('更新提示', '你确定要'+operator+'"'+deptName+'"'+'组织吗？', function(r){
			if(r){
				$.ajax({
					async : false,
					cache:false,
					type: 'POST',
					dataType : "json",
					data : {
						"department.departmentId" : departmentId,
						"department.departmentState" :value
					},
					url: 'sys/updateDepartmentStatus.action',//请求的action路径
					error: function () {//请求失败处理函数
						sysErrorShow('请求失败!');
					},success:function(data){
						if(data.success==true){//未返回任何消息表示添加成功
							sysMsgShow(operator+'成功!');
							query();
						}else{//返回异常信息
							if(data.msg='101')
							{
								sysMsgShow('修改状态失败!');
							}
						}
					}
				});
			}
		});
	} else {
		noSelectData();
	}
}

//删除组织
function delDepartment(){
	if($('#dataGridTable').datagrid('getSelected')){
		var ids = [];
		var cods = [];
		var selectedRow = $('#dataGridTable').datagrid('getSelected');
		var mainDepartmentId = selectedRow.departmentId;
		var mainDepartmentName = selectedRow.departmentName;
		var mainDepartmentParentId = selectedRow._parentId;
		if(mainDepartmentParentId == undefined){
			sysErrorShow(mainDepartmentName+",顶级组织不能删除！");
			return;
		}
		$.ajax({
			async : false,
			cache:false,
			type: 'post',
			dataType : "json",
			data : {
				"department.departmentId" : mainDepartmentId
			},
			url:"sys/queryLowerDepartmentAssociate.action",
			error: function () {
				sysErrorShow('请求失败');
			},success:function(data){
				if(data.success==true){
					if(data.rows.length > 1){
						sysErrorShow('"'+mainDepartmentName+'"组织还有下级组织，下级组织删除后才能删除。');
					} else {
						$.messager.confirm('删除提示', '你确定删除"'+mainDepartmentName+'"组织?', function(r){
							if (r){
								var url = 'sys/deleteDepartment.action?department.departmentId='+mainDepartmentId;
								$.ajax({
									async : false,
									cache:false,
									type: 'post',
									dataType : "json",
									url:url,
									error: function () {
										sysErrorShow('请求失败');
									},success:function(data){
										if(data.success==true){
											sysMsgShow("删除成功!");
											query();
										}else{
											sysErrorShow(data.msg);
										}
									}
								});
							}
						});
					}
					
				}else{
					sysErrorShow(data.msg);
				}
			}
		});
		
	}
	else
	{
		noSelectData();
	}
}

//查询
function query()
{
	if($('#departmentSearchForm').form('validate')){
		var searchDeptCode = $("#searchDeptCode").textbox('getValue');
		var searchDeptName = $("#searchDeptName").textbox('getValue');
		if(searchDeptCode == '' && searchDeptName == ''){
			$('#dataGridTable').treegrid({ url:"sys/queryDepartment.action",
				method:"post"
			});
		} else {
			$('#dataGridTable').treegrid({
				url:"sys/queryDepartmentAssociate.action",
				queryParams:{"department.departmentCode":searchDeptCode,
						     "department.departmentName":searchDeptName
						    },
				method:"post"
			});
		}
		$('#dataGridTable').datagrid("unselectAll");
	} else {
		sysErrorShow("查询数据校验不成功！");
	}
}

//打开添加组织窗口
function addDepartment(){
	if($('#dataGridTable').treegrid('getSelected')){
		//获取选中的值
		var row = $('#dataGridTable').treegrid('getSelections')[0];
		loadSelectData(row.departmentId,'');
	} else {
		loadSelectData('','');
	}
	openDialog_add();
}

//保存组织信息
function departmentSave(){
	var validateResult = $('#departmentEditForm').form('validate');
	//easyui 表单验证
	if(validateResult==false){
		sysErrorShow('必填项未填或数据格式有误！');
		return;
	}
	//获取grid选中的数据
	var departmentId = $("#edit_department_id").val();
	var departmentParentId = $("#edit_department_parent_id").combotree("getValue");
	var departmentParentName = $("#edit_department_parent_id").combotree("getText");
	var departmentCode = $("#edit_department_code").textbox("getValue");
	var departmentName = $("#edit_department_name").textbox("getValue");
	var departmentStatus = $("#edit_department_status").val();
	if(departmentStatus == undefined ||departmentStatus == ''){
		departmentStatus = '1';
	}
	//请求组织
	$.ajax({
		async : false,
		cache:false,
		type: 'POST',
		dataType : "json",
		data : {
				"department.departmentId" : departmentId,
				"department.parentId" : departmentParentId,
				"department.parentName" : departmentParentName,
				"department.departmentCode" : departmentCode,
				"department.departmentName" : departmentName,
				"department.departmentState" : departmentStatus
			},
		url: 'sys/saveDepartment.action',//请求的action路径
		error: function () {//请求失败处理函数
			sysErrorShow('组织保存失败');
		},success:function(data){
			if(data.success==true){//未返回任何消息表示添加成功
				sysMsgShow("保存成功");
				query();
				closeDepartmentDialog();
			}else{//返回异常信息
				sysErrorShow(data.msg);
			}
		}
	});
	
}

//修改组织信息
function editDepartment(){
	if($('#dataGridTable').treegrid('getSelected')){
		var row = $('#dataGridTable').treegrid('getSelections')[0];
		$("#edit_department_id").val(row.departmentId);
		$("#edit_department_code").textbox("setValue",row.departmentCode);
		$("#edit_department_name").textbox("setValue",row.departmentName);
		$("#edit_department_status").val(row.departmentState);
		loadSelectData(row.parentId,row.departmentId);
		openDialog_add();
		$('#departmentEdit').dialog('setTitle','编辑组织'); 
	}
	else
	{
		noSelectData();
	}
}

//加载数据
function loadSelectData(value,exclued){
	window.bgidx = {treeNotLeafSelected:true};
	$('#edit_department_parent_id').combotree({    
	    url:'sys/queryDepartment.action?department.excludeId='+exclued,    
	    valueField:'id',
	    width:249,
	    textField:'text',
	    loadFilter: function(data){   
        	return data.rows;   
    	},
    	onLoadSuccess:function(node, data){   
    		$('#edit_department_parent_id').combotree('setValue',value);
    	}
	});
	
	
}

//初始化编辑框
function openDepartmentDialog(){
	$('#departmentEdit').dialog({
		title : '编辑组织',
		modal: true,      	//模式窗口：窗口背景不可操作
		collapsible : true,  	//可折叠，点击窗口右上角折叠图标将内容折叠起来
		resizable : true,    	//可拖动边框大小
		onClose : function(){   //继承自panel的关闭事件
			initDepartmentDiv();
		}
	});
}

//关闭添加或修改窗口
function closeDepartmentDialog(){
	$('#departmentEdit').dialog('close');
}

//打开添加或修改模窗
function openDialog_add(){ 
	$('#departmentEdit').dialog({
		closed: false,
		modal:true,
        title: "新增组织",
        buttons: [{
            text: '确定',
            iconCls: 'icon-ok',
            handler: departmentSave
        }, {
            text: '取消',
            iconCls: 'icon-cancel',
            handler: function () {
            	closeDepartmentDialog();                    
            }
        }]
    });
}

//刷新表格，清空条件
function refresh(){
	$("#searchDeptCode").textbox('setValue','');
	$("#searchDeptName").textbox('setValue','');
 	$('#dataGridTable').treegrid({url:"sys/queryDepartment.action",
 		queryParams:[],
		method:"post"
	});
 	//$('#dataGridTable').datagrid().unselectAll();
}

//清空控件值
function initDepartmentDiv(){
	$("#edit_department_id").val('');
	$("#edit_department_parent_id").combotree('setValue','');
	$("#edit_department_code").textbox("setValue","");
	$("#edit_department_name").textbox("setValue","");
	$("#edit_department_status").val("");
}

//状态转换
function areaSatuts(value,row,index){
	var text='';
	if(value=='0'){
		text='<image src="resources/images/icons/stop.png"/>';
	}
	else if(value=='1'){
		text='<image src="resources/images/icons/yes.png"/>';
	}
	return text;
}
